import React, {Component} from 'react';

import Welcome from "../components/welcome/Welcome";
import {Post} from "../components/posts/Post";

import * as API from '../shared/http';

// eslint-disable-next-line
import parseLinkHeader from 'parse-link-header'
import orderBy from 'lodash/orderBy'
import Ad from "../components/ad/Ad";
import CreatePost from "../components/posts/Create";
import Posts from "../components/posts/Posts";


class Home extends Component{
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      posts: [],
      endpoint: `${process.env.REACT_APP_SERVE_API}/posts?_page=1&_sort=date&_order=DESC&_embed=comments&_expand=user&_embed=likes`,
      noPost: false,
    };

    this.getPosts = this.getPosts.bind(this);
    this.createNewPost = this.createNewPost.bind(this);
  }


  createNewPost(post){
    return API.createPost(post)
        .then(res => {
          return res.json()
              .then(newPost => {

                this.setState(prevState => {
                  return {
                    posts: orderBy(prevState.posts.concat(newPost),'date','desc')
                  }
                })
              })
              .catch(err => {
                this.setState(() => ({error: err}))
              })
        })
  }
  componentDidMount(){
    this.getPosts();
  }

  /**
   * url 链接
   * page 分页数
   */
  pageNumber(url){
    // 获取 _page=0 的 0下标具体位置
    let pageIndex = url.indexOf('_page=')+'_page='.length; // 35
    // 截取相应的 分页数
    let pageNumber = +url.charAt(pageIndex);
    pageNumber++; // 自增
    return `${url.substring(0,pageIndex)}${pageNumber}${url.substring(pageIndex+1)}`;

  }
  getPosts(){
    console.log("endpoint",this.state.endpoint);
    API.fetchPosts(this.state.endpoint)
        .then(res => {
          return res.json().then(posts => {

            return this.setState(() => ({
              noPost: posts.length < 10, // 文章小于10，就表示后面的分页肯定也是没有的了
              posts: orderBy(this.state.posts.concat(posts),'date','desc'),
              endpoint: this.pageNumber(this.state.endpoint),
            }))

          })
        })
        .catch(err => {
          this.setState(() => ({error: err}))
        })
  }

  render() {
    return (
        <div className="home">
          {/* <div><div class="left"></div></div> */}
          <Welcome key="welcome" />
          <div className="center">
            <CreatePost onSubmit={this.createNewPost} user={this.props.user} />
            {this.state.posts.length > 0 && (
                <div className="posts">
                  <Posts posts={this.state.posts} user={this.props.user} />
                  {/*{this.state.posts.map( ({id}) => {*/}
                  {/*  return <Posts key={id} id={id} user={this.props.user} />*/}
                  {/*})}*/}
                </div>
            )}
            <button className="block" onClick={this.getPosts} disabled={this.state.noPost ? true : false} >
              {this.state.noPost ? '文章数量不够，请多多发表文章哦！' : '加载更多帖子'}
            </button>
          </div>
          <div className="right">
            <Ad
                url="https://ifelse.io/book"
                imageUrl={`${process.env.REACT_APP_SERVE_STATIC}/assets/ads/ria.png`}
            />
            <Ad
                url="https://ifelse.io/book"
                imageUrl={`${process.env.REACT_APP_SERVE_STATIC}/assets/ads/orly.jpg`}
            />
          </div>
        </div>
    )
  }
}

export default Home;
